﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using PortableVersion.Core.General;
using System.Linq;

namespace PortableVersion.Core.SourceControl.CommandLine
{
    public class SourceControlConfigItem
    {
        [XmlAttribute]
        public string Key { get; set; }
        [XmlAttribute]
        public string Value { get; set; }
        public SourceControlConfigItem(string key, string val)
        {
            Key = key;
            Value = val;
        }
        public SourceControlConfigItem()
        {
        }
    }

    public class SourceControlConfiguration
    {
        public string Command { get; set; }

        [XmlArray]
        public List<SourceControlConfigItem> ConfigParamPatternDefinitions { get; set; }
        [XmlIgnore]
        public IDictionary<string, string> ParamPatternDefinitions { get; private set; }

        public void Save(string path)
        {
            SerializationHelper.Save(this, path);
        }

        public static SourceControlConfiguration Load(string path)
        {
            var rv = SerializationHelper.Load<SourceControlConfiguration>(path);
            rv.ParamPatternDefinitions = rv.ConfigParamPatternDefinitions.ToDictionary(kv => kv.Key, kv => kv.Value);
            return rv;
        }

        public string GetCommand(SourceControlActions action, IEnumerable<KeyValuePair<SourceControlParam, string>> pars)
        {
            string parCommand;
            if(ParamPatternDefinitions.TryGetValue(Enum.GetName(typeof(SourceControlActions), action), out parCommand))
            {
                return SourceControlCommandLineHelper.GetCommand(parCommand, pars);
            }
            throw new ArgumentException(@"SourceControl Action is not configured.", "action");
        }

    }
}
